'use strict';

var ydylServices = angular.module('ydylServices', ['ngCookies']);

ydylServices.factory('Phone', ['$resource',
    function($resource){
        return $resource('phones/:phoneId.json', {}, {
            query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
        });
    }]);

app.factory(
    "transformRequestAsFormPost",
    function () {
        // I prepare the request data for the form post.
        function transformRequest(data) {
            return ( serializeData(data) );
        }

        // Return the factory value.
        return ( transformRequest );
        // ---
        // PRVIATE METHODS.
        // ---
        // I serialize the given Object into a key-value pair string. This
        // method expects an object and will default to the toString() method.
        // --
        // NOTE: This is an atered version of the jQuery.param() method which
        // will serialize a data collection for Form posting.
        // --
        // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
        function serializeData(data) {
            // If this is not an object, defer to native stringification.
            if (!angular.isObject(data)) {
                return ( ( data == null ) ? "" : data.toString() );
            }
            var buffer = [];
            // Serialize each key in the object.
            for (var name in data) {
                if (!data.hasOwnProperty(name)) {
                    continue;
                }
                var value = data[name];
                buffer.push(
                    encodeURIComponent(name) +
                    "=" +
                    encodeURIComponent(( value == null ) ? "" : value)
                );
            }
            // Serialize the buffer and clean it up for transportation.
            var source = buffer
                .join("&")
                .replace(/%20/g, "+")
                ;
            return ( source );
        }
    }
);

ydylServices.factory('controllerData', function($rootScope, $cookies, myHttp) {
    return {
        selectedDoctors: [],
        selectedFile: [],
        token :$cookies.get('memberToken'),
        mobile :$cookies.get('memberMobile'),
        currentMember: null,
        currentConsult: null,
        selectedPatient:null,
        getMember:function (callback) {
            var _this = this;
            if(_this.currentMember!=null)
                return _this.currentMember;
            else{
                myHttp.jsonp('apiDoctor/getDoctorInfo?doctormobile='+_this.mobile+'&token=&time_stamp=&targetmobile='+_this.mobile , function (result) {
                    _this.currentMember = result.items[0];
                    callback(_this.currentMember);
                });
            }
        },
        getConsultDetail:function (id, callback) {
            var _this = this;
            myHttp.jsonp('apiConsultOrder/consultDetail?doctormobile=' + this.mobile + '&token=' + this.token + '&time_stamp=' + new Date().getTime() + '&consultid=' + id, function (result) {
                $rootScope.info = result.items[0];
                _this.currentConsult = result.items[0];
                if(callback)
                    callback(result);
            });
        }
    }
});

ydylServices.factory('scrollPager', function(myHttp, $http, controllerData) {
    var scrollPager = function(url) {
        this.items = [];
        this.busy = false;
        this.after = 1;
        this.url = url;
        this.prevTime = new Date().getTime()-2000;
        this.callback = null;
    };
    scrollPager.prototype.changeUrl = function (url) {
        this.url =url;
    }
    scrollPager.prototype.nextPage = function() {
        var now = new Date().getTime();
        if(now - this.prevTime < 2000) return;
        this.prevTime = now;
        if (this.busy) return;
        this.busy = true;

        myHttp.jsonp(this.url.replace('{after}', this.after), function (result) {
            if(result.items && result.items.length>0) {
                var items = result.items;
                for (var i = 0; i < items.length; i++) {
                    this.items.push(items[i]);
                }
                if(this.callback) this.callback();
            }
            this.after ++;
            this.busy = false;
        }.bind(this), true)
    };

    return scrollPager;
});

ydylServices.factory('scrollPager01', function(myHttp01, $http, controllerData) {
    var scrollPager = function(url) {
        this.items = [];
        this.busy = false;
        this.noRecord = false;
        this.after = 1;
        this.url = url;
        this.prevTime = new Date().getTime()-2000;
        this.callback = null;
    };
    scrollPager.prototype.changeUrl = function (url) {
        this.url =url;
    }
    scrollPager.prototype.nextPage = function() {
        var now = new Date().getTime();
        if(now - this.prevTime < 2000) return;
        this.prevTime = now;
        this.noRecord = false;
        if (this.busy) return;
        this.busy = true;


        myHttp01.jsonp(this.url.replace('{after}', this.after), function (result) {
            if(result.items && result.items.length>0) {
                var items = result.items;
                for (var i = 0; i < items.length; i++) {
                    this.items.push(items[i]);
                }
                this.noRecord = false;
                if(this.callback) this.callback();
            }else{

                this.noRecord = true;

            }
            this.after ++;
            this.busy = false;
        }.bind(this), true)
    };

    return scrollPager;
});


ydylServices.factory('myHttp01',
    function($http,transformRequestAsFormPost ){
        var apiBase ='http://101.201.72.223:8888/yby-0.1/';

        return{
            jsonp:function (apiPath, callback, forceCallback) {

                var apiUrl = apiBase + apiPath + '&callback=JSON_CALLBACK';
                $http.jsonp(apiUrl).then(function(response) {
                    if(response.data.ret=='0' && !forceCallback && response.data.msg!='暂无数据！')
                        alert(response.data.msg);
                    else
                        callback(response.data)
                }, function(response) {
                    console.log(response);
                    var names="";
                    for(var name in response){
                        names+=name+": "+response[name]+", ";
                    }
                    alert(names);
                });
            },
            get:function (apiPath, callback) {

                var apiUrl = apiBase + apiPath;
                $http.get(apiUrl)
                    .success(function(data,header,config,status){
                        if(data.ret=='0')
                            alert(data.msg);
                        else
                            callback(data)
                    }).error(function(data,header,config,status){
                        alert('未知异常'+data);
                        console.log(data);
                    });
            },
            post:function (apiPath, data, callback) {
                var apiUrl = apiBase + apiPath;
                $http({
                    method: "POST",
                    url: apiUrl,
                    transformRequest: transformRequestAsFormPost,
                    data: data,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                })
                    .success(function(data,header,config,status){
                        callback(data);
                    }).error(function(data,header,config,status){
                        console.log(data);
                    });;
            }
        }
    });

ydylServices.factory('myHttp',
    function($http,transformRequestAsFormPost ){
        var apiBase ='http://101.201.72.223/ydyl/';

        return{
            jsonp:function (apiPath, callback, forceCallback) {

                var apiUrl = apiBase + apiPath + '&callback=JSON_CALLBACK';
                $http.jsonp(apiUrl).then(function(response) {
                    if(response.data.ret=='0' && !forceCallback && response.data.msg!='暂无数据！')
                        alert(response.data.msg);
                    else
                        callback(response.data)
                }, function(response) {
                    console.log(response);
                    var names="";
                    for(var name in response){
                        names+=name+": "+response[name]+", ";
                    }
                    alert(names);
                });
            },
            get:function (apiPath, callback) {

                var apiUrl = apiBase + apiPath;
                $http.get(apiUrl)
                    .success(function(data,header,config,status){
                        if(data.ret=='0')
                            alert(data.msg);
                        else
                            callback(data)
                    }).error(function(data,header,config,status){
                        alert('未知异常'+data);
                        console.log(data);
                    });
            },
            post:function (apiPath, data, callback) {
                var apiUrl = apiBase + apiPath;
                $http({
                    method: "POST",
                    url: apiUrl,
                    transformRequest: transformRequestAsFormPost,
                    data: data,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                })
                    .success(function(data,header,config,status){
                        callback(data);
                    }).error(function(data,header,config,status){
                        console.log(data);
                    });;
            }
        }
    }
);